package ae.pcfc.cldos.online.web.controller.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.controller.base.BasePageController;
import ae.pcfc.cldos.online.web.services.security.beans.LoginBean;

/**
 * 
 * 
 * @author Andriy
 * @Reviewed By Ammar
 */
@Controller
public class LoginController extends BasePageController {
		
	@Autowired
	@Qualifier("preAuthenticatedProcessingFilterEntryPoint")
	private AuthenticationEntryPoint authenticationEntryPoint;
	
	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * /register/form.jsp
	 * @see #form(HttpServletRequest,SessionStatus,Register, BindingResult)
	 * @see WEB-INF/jsp/login.jsp
	 */
	@RequestMapping(value = ViewPath.__LOGIN, method = RequestMethod.GET)
	public ModelAndView login() {
		if(!securityService.isAuthenticated()){
				return new ModelAndView(ViewPath.__LOGIN);
		} else {
			return new ModelAndView(ViewPath.__FORWARD+ViewPath.__INDEX);
		}
	}
	
	@RequestMapping(value = ViewPath.__LOGIN, method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, 
			@ModelAttribute LoginBean loginBean, BindingResult errors) {
		
		if(securityService.login(request, response, loginBean)){
			return new ModelAndView(ViewPath.__FORWARD+ViewPath.__INDEX);
		} else {
			return login();
		}
	}
	
	@RequestMapping(value = ViewPath.__REDIR_TO_LOGIN)
	public void redirtologin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		authenticationEntryPoint.commence(request, response, null);
	}
}
